<?php
	/**
	 * 助手function
	 * @author haifeng
	 * @time  20141009
	 */
if(!function_exists('get_client_ip')){
	/**
	 * 获取客户端IP地址
	 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字 默认1
	 * @param boolean $adv 是否进行高级模式获取（有可能被伪装） 默认true
	 * @return mixed
	 */
	function get_client_ip($type = 1,$adv=true) {
		$type       =  $type ? 1 : 0;
		static $ip  =   NULL;
		if ($ip !== NULL) return $ip[$type];
		if($adv){
			if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
				$arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
				$pos    =   array_search('unknown',$arr);
				if(false !== $pos) unset($arr[$pos]);
				$ip     =   trim($arr[0]);
			}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
				$ip     =   $_SERVER['HTTP_CLIENT_IP'];
			}elseif (isset($_SERVER['REMOTE_ADDR'])) {
				$ip     =   $_SERVER['REMOTE_ADDR'];
			}
		}elseif (isset($_SERVER['REMOTE_ADDR'])) {
			$ip     =   $_SERVER['REMOTE_ADDR'];
		}
		// IP地址合法验证
		$long = sprintf("%u",ip2long($ip));
		$ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
		return $ip[$type];
	}
 }

 if(!function_exists('getHttpHost')){
	/**
	 * Get the HTTP host.
	 * @return string
	 */
	function getHttpHost()
    {
        $host = $_SERVER['HTTP_HOST'];
        if (!empty($host)) {
            return $host;
        }

        $scheme = getScheme();
        $name   = $_SERVER['SERVER_NAME'];
        $port   = $_SERVER['SERVER_PORT'];

        if(null === $name) {
            return '';
        }
        elseif (($scheme == 'http' && $port == 80) || ($scheme == 'https' && $port == 443)) {
            return $name;
        } else {
            return $name . ':' . $port;
        }
    }
}

if(!function_exists('getScheme')){
	/**
	 * 获取协议
	 * @return string
	 */
	function getScheme(){
		return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http';
	}
}